import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core'
import { ISearchSchema } from '@shared/interfaces/search'
import * as dayjs from 'dayjs'
import { NzMessageService } from 'ng-zorro-antd'
import { EDateLimitEnum } from '@shared/interfaces/common'
import { I18NService } from '@core'

@Component({
  selector: 'app-search',
  templateUrl: './search-component.html',
  styleUrls: ['./search-component.less'],
})
export class SearchComponent implements OnInit {
  @Input()
  @Output()
  data: ISearchSchema[]

  @Input() customItems: ISearchSchema[]
  @Output() bindSearch = new EventEmitter()

  chosenItem: ISearchSchema
  @ViewChild('customOption') customOption

  allowClear = true
  constructor(public msg: NzMessageService, private i18n: I18NService) {}

  ngOnInit() {}

  search(): void {
    this.bindSearch.next(this.data)
  }

  maxLength(index: string): string {
    switch (index) {
      case 'username':
        return '20'
      case 'nickName':
        return '50'
      default:
        return '120'
    }
  }

  changeCustomItem(indexValue: string): void {
    this.chosenItem = this.customItems.find(item => item.index === indexValue)
  }

  addCustomItem(): void {
    if (!this.chosenItem) {
      return
    }
    /* 将 chosenItem 加入到 data 中，记得加上 custom 的标志 */
    Object.assign(this.chosenItem, { custom: true })
    this.data.push(this.chosenItem)

    /* 将这个 chosenItem 从 customItems 中去除， 并将 chosenItem 置空  */
    this.customItems.forEach((item, index) => {
      if (item.index === this.chosenItem.index) {
        this.customItems.splice(index, 1)
      }
    })
    this.chosenItem = undefined
    this.customOption.value = ''
    console.log('option', this.customOption)
  }

  disabledDate = (current: Date): boolean => {
    const today = new Date()
    // Can not select days before today and today
    return current > today
  }

  removeCustomItem(item: ISearchSchema): void {
    this.data.reverse().forEach((dataItem, index) => {
      if (dataItem.index === item.index) {
        this.data.splice(index, 1)
      }
    })
    this.data.reverse()
    this.customItems.push(item)
  }

  handleRangePickerChange(dates: Date[], limitType: EDateLimitEnum = EDateLimitEnum.Year, bindingDates): void {
    const [firstDate, secondDate] = dates
    let isOverLimit = false
    switch (limitType) {
      case EDateLimitEnum.Year:
        isOverLimit = dayjs(secondDate).isAfter(dayjs(firstDate).add(1, 'year'))
        break
      case EDateLimitEnum.Month:
        isOverLimit = dayjs(secondDate)
          .add(1, 'day')
          .isAfter(dayjs(firstDate).add(31, 'day'))
        break
    }
    if (isOverLimit) {
      this.msg.error(this.i18n.fanyi('GENERAL.NOTIFICATION.SEARCH_TIME.OUT_OF_RANGE'))
      const today = dayjs()
        .startOf('day')
        .format('YYYY-MM-DDTHH:mm:ssZ')
      bindingDates.value = [today, today]
    }
  }
}
